package dao

import (
	"go_my_framework/app/core/db"
	"go_my_framework/app/model"
	"time"
)

type ArticleDao interface {
	FindRow(id int, title string) model.Article
	GetList(page int, limit int, title string) ([]model.Article, int64, error)
	Create(title string, desc string, content string, coverImage string, isOpenComment int8, isTop int8, isRecommended int8, adminId int) (int, error)
	Update(id int, title string, desc string, content string, coverImage string, isOpenComment int8, isTop int8, isRecommended int8, adminId int) error
	Del(id int) error
}

func NewArticleDaoImpl() ArticleDao {
	return new(ArticleDaoImpl)
}

type ArticleDaoImpl struct {

}

func (a *ArticleDaoImpl) FindRow(id int, title string) (data model.Article) {
	obj := db.Instance().Model(model.Article{})
	if id != 0 {
		obj.Where("id = ?", id)
	}
	if title != "" {
		obj.Where("title = ?", title)
	}
	obj.First(&data)
	return data
}

func (a *ArticleDaoImpl) GetList(page int, limit int, title string) (data []model.Article, count int64, err error) {
	obj := db.Instance().Model(model.Article{})
	if title != "" {
		obj = obj.Where("title = ?", title)
	}
	obj = obj.Count(&count)
	err = obj.Limit(limit).Offset((page - 1) * limit).Order("id desc").Find(&data).Error
	return
}

func (a *ArticleDaoImpl) Create(title string, desc string, content string, coverImage string, isOpenComment int8, isTop int8, isRecommended int8, adminId int) (int, error) {
	dateTime := time.Now().Format("2006-01-02 15:04:05")
	data := model.Article{
		Title:         title,
		Desc:          desc,
		Content:       content,
		CoverImage:    coverImage,
		IsOpenComment: isOpenComment,
		IsTop:         isTop,
		IsRecommended: isRecommended,
		AdminId:       adminId,
		PublishDt:     dateTime,
	}
	err := db.Instance().Model(&model.Article{}).Create(&data).Error
	if err != nil {
		return 0, err
	} else {
		return data.Id, nil
	}
}

func (a *ArticleDaoImpl) Update(id int, title string, desc string, content string, coverImage string, isOpenComment int8, isTop int8, isRecommended int8, adminId int) error {
	//dateTime := time.Now().Format("2006-01-02 15:04:05")
	data := map[string]interface{}{
		"title":           title,
		"desc":            desc,
		"content":         content,
		"cover_image":     coverImage,
		"is_open_comment": isOpenComment,
		"is_top":          isTop,
		"is_recommended":  isRecommended,
		"admin_id":        adminId,
	}
	return db.Instance().Model(model.Article{}).Where("id = ?", id).Updates(data).Error
}

func (a *ArticleDaoImpl) Del(id int) error {
	return db.Instance().Where("id = ?", id).Delete(model.Article{}).Error
}